<?php
/**
 * DBERP 进销存系统
 *
 * ==========================================================================
 * @link      http://www.dberp.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   http://www.dberp.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Filter;

use Laminas\Filter\AbstractFilter;

class ImageRegenerate extends AbstractFilter
{
    public function __construct($options = [])
    {

    }

    public function filter($value)
    {
        $image = $value['tmp_name'];

        if (substr($image, -4) == '.ico') return $value;

        list($width, $height) = getimagesize($image);

        $newImage   = imagecreatetruecolor($width, $height);

        switch (substr($image, -4)) {
            case '.jpg':
            case '.jpe':
                $sourceImage = imagecreatefromjpeg($image);
                imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $width, $height, $width, $height);
                imagejpeg($newImage, $image);
                imagedestroy($newImage);
                imagedestroy($sourceImage);
                break;
            case '.png':
                $sourceImage = imagecreatefrompng($image);
                imagealphablending($newImage, false);
                imagesavealpha($newImage, true);
                imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $width, $height, $width, $height);
                imagepng($newImage, $image);
                imagedestroy($newImage);
                imagedestroy($sourceImage);
                break;
            case '.gif':
                $sourceImage = imagecreatefromgif($image);
                imagealphablending($newImage, false);
                imagesavealpha($newImage, true);
                imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $width, $height, $width, $height);
                imagegif($newImage, $image);
                imagedestroy($newImage);
                imagedestroy($sourceImage);
                break;
            default:
                @unlink($image);
                $value = [];
                break;

        }

        return $value;
    }
}